package com.example.mobile2121606109ycg0524homework1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class MyDataAdapter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;

    public void openDB(Context context) {
        openHelper = new MySQLiteOpenHelper(context,"factory.db",null,1);
        try {
            database = openHelper.getWritableDatabase();
        }catch (Exception e){
            database = openHelper.getReadableDatabase();
        }
    }

    public void closeDB() {
        if (database != null){
            database.close();
            database = null;
        }
        if (openHelper != null){
            openHelper.close();
            openHelper = null;
        }
    }

    public List<Staff> QueryAll(Context context){
        List<Staff> staffList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("staff",null,null,null,null,null,null);
        if (cursor.moveToFirst()){
            do {
                String name = cursor.getString(1);
                String skill = cursor.getString(2);
                String salary = cursor.getString(3);
                staffList.add(new Staff(name, skill,salary));
            }while (cursor.moveToNext());
        }
        cursor.close();
        closeDB();
        return staffList;
    }

    public long insert(Context context, Staff staff){
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("name", staff.getName());
        values.put("skill", staff.getSkill());
        values.put("salary", staff.getSalary());
        long result = database.insert("staff",null,values);
        closeDB();
        return result;
    }
}
